package com.HuiShou.service.impl;

import com.HuiShou.domain.UserPointsAccount;
import com.HuiShou.domain.UserPointsDetail;
import com.HuiShou.mapper.UserPointsAccountMapper;
import com.HuiShou.mapper.UserPointsDetailMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
@RequiredArgsConstructor
public class PointsService {
    @Autowired
    private  UserPointsAccountMapper accountMapper;
    @Autowired
    private  UserPointsDetailMapper detailMapper;

    @Transactional(propagation = Propagation.MANDATORY)  // 必须在事务中调用
    public void addPoints(Long userId, BigDecimal amount, String type, String bizId) {
        // 使用悲观锁确保并发安全
        UserPointsAccount account = accountMapper.selectForUpdate(userId);
        if (account == null) {
            account = new UserPointsAccount();
            account.setUserId(userId);
            account.setBalance(amount);
            accountMapper.insert(account);
        } else {
            account.setBalance(account.getBalance().add(amount));
            accountMapper.updateByIdD(account.getBalance(),account.getUserId());
        }

        // 记录积分明细
        UserPointsDetail detail = new UserPointsDetail();
        detail.setUserId(userId);
        detail.setChangeAmount(amount);
        detail.setCurrentBalance(account.getBalance());
        detail.setType(type);
        detail.setBizId(bizId);
        detail.setRemark("订单完成奖励 - 订单号：" + bizId);
        detailMapper.insert(detail);
    }
}
